//
//  ViewController.m
//  NSThreadUsing
//
//  Created by 方正刚 on 2017/7/20.
//  Copyright © 2017年 方正刚. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic, assign) NSInteger tickets;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tickets = 10;
    
    // 测试开启线程
    [self tesstFour];
    

}




// 模拟卖票 点击屏幕开始售票
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(sellTickets) object:nil];
    
    [thread1 start];

    NSThread *thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(sellTickets) object:nil];
    
    [thread2 start];
    
}


/**
 卖票的方法 线程是不安全的 调用这个方法卖票系统会错乱
 */
//- (void)sellTickets {
//    
//    while (YES) {
//        if (self.tickets > 0) {
//            self.tickets = self.tickets - 1;
//            NSLog(@"剩余%ld张票", self.tickets);
//        }else {
//            NSLog(@"票卖完了");
//        }
//        
//    }
//}


/**
 卖票的方法 卖票加入读写同步 保证数据正确
 */
- (void)sellTickets {
    
    // 任意一个对象内部都有一把锁 默认锁是开着的
    // 互斥锁
    // 线程同步
    @synchronized (self) {
        while (YES) {
            if (self.tickets > 0) {
                self.tickets = self.tickets - 1;
                NSLog(@"剩余%ld张票", self.tickets);
            }else {
                NSLog(@"票卖完了");
            }
            
        }

    }
    
}





/**
 方法一
 */
- (void)testOne {
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(threadTest) object:nil];
    
    [thread start];
}


/**
 方法二
 */
- (void)testTwo {
    [NSThread detachNewThreadSelector:@selector(threadTest) toTarget:self withObject:nil];
}


/**
 方法三
 */
- (void)testThree {
    [self performSelectorInBackground:@selector(threadTest) withObject:nil];
}


/**
 传递参数
 */
- (void)tesstFour {
    [self performSelectorInBackground:@selector(threadTest:) withObject:@"线程的创建者"];
}


/**
 线程执行的方法无参数
 */
- (void)threadTest {
    NSLog(@"threadTest所在线程 -- %@", [NSThread currentThread]);
}

- (void)threadTest:(NSString *)name {
    NSLog(@"threadTest -- %@", name);
}






@end
